<?php

include_once 'convert.php';

/*
 * Usage:
 * ldb_query_complete(sql);
 * Parameter:
 * sql - SQL query for the database
 * Return:
 * Returns the result of the query and NULL if the query failed
 */
function ldb_query_complete($sql) {
    /* Connecting with database */
    $con = ldb_connect();

    /*Handling connection errors*/
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
        return false;
    } else
    {
        $result = mysqli_query($con,$sql);
        /*Handling query errors and making query*/
        if (!$result) {
            die('Error: ' .mysqli_error($con));
        }
        ldb_disconnect($con);
        return $result;
    }
}

/*
 * Usage:
 * ldb_connect();
 * Parameter:
 * none
 * Return:
 * Returns a connection to the local database, which can be used to make
 * queries.
 */
function ldb_connect() {
    /* Connecting with database */
    $con = mysqli_connect("127.0.0.1", "ref", "test", "finalspec");
    /*Handling connection errors*/
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
        return false;
    } else
    {
        return $con;
    }
}

/*
 * Usage:
 * ldb_query(con, sql);
 * Parameter:
 * con - Active connection to the local database
 * sql - SQL-query that is given to the database
 * Return:
 * The result of the query, or false if the connection is not valid.
 */
function ldb_query($con, $sql) {
    if (!$con) {
        return false;
    }
    $result = mysqli_query($con,$sql);
    /*Handling query errors and making query*/
    if (!$result) {
        die('Error: ' .mysqli_error($con));
    }
    return $result;
}

/* Usage:
 * ldb_disconnect();
 * Parameter:
 * none
 * Return:
 * True if disconnection was successful, false if not
 */
function ldb_disconnect($con) {
    return mysqli_close($con);
}